package com.yujn.springsecurityactual.config;

import com.yujn.springsecurityactual.pojo.UserDO;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: Yujn
 * @create: 2021-03-15 21:16
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 从数据库读取出用户 将该db交给security接管即可
        // security会验证前端传递的password
        UserDO dbUser = this.getDBUser(userName);
        if (dbUser == null){
            throw new RuntimeException("用户不存在");
        }

        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(dbUser.getRoles());
        User user = new User(userName,dbUser.getPassword(),grantedAuthorities);
        return user;
    }

    /**
     * 模拟从数据库查询出 user
     * @param userName
     * @return
     * @author yujn
     * @date 2021/3/15 21:43
     */
    public UserDO getDBUser(String userName){
        UserDO userDO = null;
        if ("user".equals(userName)){
            userDO = new UserDO();
            userDO.setUserName("user");
            userDO.setPassword(this.passwordEncoder().encode( "123"));
            userDO.setRoles("ROLE_USER,ROLE_USER_DELETE");
        }else if ("admin".equals(userName)){
            userDO = new UserDO();
            userDO.setUserName("admin");
            userDO.setPassword(this.passwordEncoder().encode( "123"));
            userDO.setRoles("ROLE_ADMIN,ROLE_USER");
        }
        return userDO;
    }
}
